package com.houger.license;

import io.jsonwebtoken.Jwts;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.time.LocalDate;
import java.util.Base64;

public class LicenseKeyGenerator {
    /**
     * 需要从目标设备获取指纹（运行/fingerprint接口）
     */
    private static final String TARGET_FINGERPRINT = "nk1mKS87|3/lxMYt8Fz7ASN9NjQrSCS1myboMuXP079PSj95G7DI=";
//    private static final String TARGET_FINGERPRINT = "UlQAJWtY|h+18EuZEcChtmASRCFJxSxan+gJI2ZTVblcjD73oijY=";



    /**
     * 授权天数
     */
    private static final int DAYS = 14;
    /**
     * 授权文件
     */
    private static final Path LICENSE_FILE = Paths.get("license.dat");

    public static void main(String[] args) throws Exception {
        // 生成RSA密钥对
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);
        KeyPair pair = keyGen.generateKeyPair();

        // 打印公钥（配置到application.yml）
        String publicKey = Base64.getEncoder().encodeToString(pair.getPublic().getEncoded());
        System.out.println("Public Key: \n" + publicKey);
        System.out.println("");
        System.out.println("---------------");


        String jwt = Jwts.builder()
            .claim("expire", LocalDate.now().plusDays(DAYS).toString())
            .claim("fingerprint", TARGET_FINGERPRINT)
            .signWith(pair.getPrivate())
            .compact();

        System.out.println("激活码: \n" + jwt);
        try {
            Files.writeString(LICENSE_FILE, jwt );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}